package com.qyhl.webtv.module_live.teletext.detail.popview;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.glide.GlideOptionsUtils;
import com.qyhl.webtv.commonlib.entity.live.ShoppingListBean;
import com.qyhl.webtv.module_live.R;
import com.qyhl.webtv.module_live.teletext.detail.popview.detail.TeleTextShopDetailPopView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import razerdp.basepopup.BasePopupWindow;

public class TeleTextShopPopView extends BasePopupWindow implements TeleTextShopContract.TeleTextShopView {
    private Activity mContext;
    private String sceneId;
    private View popupView;
    private List<ShoppingListBean> mDataList = new ArrayList<>();
    private CommonAdapter<ShoppingListBean> commonAdapter;
    private int page = 1;


    private RecyclerView recyclerView;
    private LoadingLayout loadMask;
    private SmartRefreshLayout refresh;
    private TeleTextShopPresenter mPresenter;

    public TeleTextShopPopView(Activity context, String id) {
        super(context);
        mContext = context;
        sceneId = id;
        bindEvent(context);
    }

    @Override
    protected Animation initShowAnimation() {
        return getTranslateVerticalAnimation(1f, 0, 500);
    }

    @Override
    protected Animation initExitAnimation() {
        return getTranslateVerticalAnimation(0, 1f, 500);
    }

    @Override
    public View getClickToDismissView() {
        return popupView.findViewById(R.id.click_to_dismiss);
    }


    @Override
    public View onCreatePopupView() {
        popupView = LayoutInflater.from(getContext()).inflate(R.layout.live_popview_shop_list, null);
        return popupView;
    }

    @Override
    public View initAnimaView() {
        return popupView.findViewById(R.id.popup_anima);
    }


    private void bindEvent(Activity context) {
        mPresenter = new TeleTextShopPresenter(this);
        if (popupView != null) {
            recyclerView = popupView.findViewById(R.id.recycle_view);
            loadMask = popupView.findViewById(R.id.load_mask);
            refresh = popupView.findViewById(R.id.refresh);
        }
        loadMask.setStatus(LoadingLayout.Loading);
        refresh.setRefreshHeader(new MaterialHeader(context));
        refresh.setRefreshFooter(new ClassicsFooter(context));
        refresh.setEnableLoadMore(true);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        DividerItemDecoration divider = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(context, R.drawable.live_popview_item_divider)));
        recyclerView.addItemDecoration(divider);

        recyclerView.setAdapter(commonAdapter = new CommonAdapter<ShoppingListBean>(context, R.layout.live_item_popview_shop, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShoppingListBean bean, int position) {
                holder.setText(R.id.title, bean.getItemName());

                holder.setText(R.id.score, bean.getPrice());

                if (mDataList.get(position).getStatus() == 0) {
                    if (mDataList.get(position).getStock() == 0) {
                        holder.setImageResource(R.id.sale_out, R.drawable.shop_sale_out_icon);
                        holder.setVisible(R.id.sale_out, true);
                        holder.setImageResource(R.id.exchange_btn, R.drawable.shop_exchange_btn_off);
                    } else {
                        holder.setVisible(R.id.sale_out, false);
                        holder.setImageResource(R.id.exchange_btn, R.drawable.shopping_top_exchange_btn);
                    }
                } else if (mDataList.get(position).getStatus() == 3) {
                    holder.setImageResource(R.id.sale_out, R.drawable.shop_sale_overdue_icon);
                    holder.setVisible(R.id.sale_out, true);
                    holder.setImageResource(R.id.exchange_btn, R.drawable.shop_exchange_btn_off);
                } else {
                    holder.setImageResource(R.id.sale_out, R.drawable.shop_sale_off_icon);
                    holder.setVisible(R.id.sale_out, true);
                    holder.setImageResource(R.id.exchange_btn, R.drawable.shop_exchange_btn_off);
                }

                //封面图
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(context)
                        .load(bean.getItemPic())
                        .apply(GlideOptionsUtils.getInstance().getOptions(R.drawable.cover_large_default, R.drawable.cover_large_default))
                        .into(cover);

                holder.setOnClickListener(R.id.exchange_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TeleTextShopDetailPopView shopDetailPopView = new TeleTextShopDetailPopView(context, bean.getId() + "");
                        shopDetailPopView.showPopupWindow();
                    }
                });
            }
        });


        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getShopList(sceneId, page + "");
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getShopList(sceneId, page + "");
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getShopList(sceneId, page + "");
            }
        });


        mPresenter.getShopList(sceneId, page + "");
    }


    /**
     * 生成TranslateAnimation
     *
     * @param durationMillis 动画显示时间
     * @param start          初始位置
     */
    private static Animation getTranslateVerticalAnimation(float start, float end, int durationMillis) {
        Animation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, start, Animation.RELATIVE_TO_PARENT, end);
        translateAnimation.setDuration(durationMillis);
        return translateAnimation;
    }


    @Override
    public void setList(List<ShoppingListBean> beanList, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Success);
        page++;
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        mDataList.addAll(beanList);

        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(mContext)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }
}
